package com.beerq.view_manager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.beerq.R;
import com.beerq.util.AppConfig;
import com.beerq.util.MyImageLoader;
import com.beerq.view.friends.ImageLookingActivity;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.util.ArrayList;

/**
 * 作者：minj on 2017/10/1 17:14
 * 模仿微信添加图片的管理类
 */
public class AddImageManager {

    private GridView mGridView;

    Activity mAttachActivity;

    MyGridViewAdapter mMyGridViewAdapter;

    //调用系统相册-选择图片
    private static final int IMAGE_PICKER = 1011;

    private static   int MAX_IMAGE_COUNT=1;

    public static ArrayList<ImageItem> mListImgs=new ArrayList<ImageItem>();

//    public static HashMap<String,SoftReference<Bitmap>> imageCache=new HashMap<String,SoftReference<Bitmap>>();

     public AddImageManager(Activity context){
         this(context,MAX_IMAGE_COUNT);
         mAttachActivity=context;
     }

    public AddImageManager(Activity context,int max_image_count){
        mAttachActivity=context;
        MAX_IMAGE_COUNT=max_image_count;

        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new MyImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(MAX_IMAGE_COUNT);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素

    }

    private  void getImageFromSystem(){
        //调用相册
        Intent intent = new Intent(mAttachActivity, ImageGridActivity.class);
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setSelectLimit(MAX_IMAGE_COUNT-mListImgs.size());    //选中数量限制
        mAttachActivity.startActivityForResult(intent, IMAGE_PICKER);
    }


    public void refresh(){
//        clearBitMap();
        showImage(new ArrayList<ImageItem>());

    }

//    public void clearBitMap(){
//        Set<String> setStr=AddImageManager.imageCache.keySet();
//
//        for (String  str : setStr){
//            Bitmap bitmap=(Bitmap)AddImageManager.imageCache.get(str).get();
//            if(bitmap!=null){
//                bitmap.recycle();
//                bitmap=null;
//            }
//
////            AddImageManager.imageCache.remove(str);
//
//        }
//    }


    public void refreshImages(){
        mMyGridViewAdapter.notifyDataSetChanged();
    }

     public void bind(){
         mGridView=(GridView)mAttachActivity.findViewById(R.id.img_grid_view);
         mMyGridViewAdapter=new MyGridViewAdapter(mAttachActivity,mListImgs );
         mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 if(view.getTag()!=null){
                     getImageFromSystem();
                 }else {
                     Intent intent=new Intent(mAttachActivity,ImageLookingActivity.class);
                     intent.putExtra(ImageLookingActivity.EXTRA_IMAGE_INDEX,position);
                     mAttachActivity.startActivity(intent);

//                     Intent intent = new Intent(mAttachActivity, ImagePreviewActivity.class);
//                     intent.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//
//                     // 但采用弱引用会导致预览弱引用直接返回空指针
//                     DataHolder.getInstance().save(DataHolder.DH_CURRENT_IMAGE_FOLDER_ITEMS, mListImgs);
//                     intent.putExtra(ImagePreviewActivity.ISORIGIN, false);
//                     intent.putExtra(ImagePicker.EXTRA_FROM_ITEMS, false);
//                     mAttachActivity.startActivityForResult(intent, ImagePicker.REQUEST_CODE_PREVIEW);  //如果是多选，点击图片进入预览界面


                 }
             }
         });

         mGridView.setAdapter(mMyGridViewAdapter);
     }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //获取图片路径
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                showImage(images);
            }
        }
    }

    //加载图片
    private void showImage(ArrayList<ImageItem> imgPath){
        mListImgs.addAll(imgPath);
        mMyGridViewAdapter.setList(mListImgs);
        mMyGridViewAdapter.notifyDataSetChanged();
    }

    public ArrayList<ImageItem> getImages(){
        return mListImgs;
    }


    static class MyGridViewAdapter extends BaseAdapter {
        //上下文对象
        private Context context;

        private ArrayList<ImageItem> lists;

        public void setList(ArrayList<ImageItem> lists){
            this.lists=lists;
        }

        MyGridViewAdapter(Context context, ArrayList<ImageItem> lists){
            this.context = context;
            this.lists=lists;
        }

        @Override
        public int getCount() {
            if(lists.size()<MAX_IMAGE_COUNT){
                return  lists.size()+1;
            }
            return lists.size();
        }

        @Override
        public Object getItem(int item) {
            return item;
        }

        @Override
        public long getItemId(int id) {
            return id;
        }

        //创建View方法
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(AppConfig.deviceDensity*80,AppConfig.deviceDensity*80));//设置ImageView对象布局
                imageView.setAdjustViewBounds(false);//设置边界对齐
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);//设置刻度的类型
                imageView.setPadding(8, 8, 8, 8);//设置间距
            }
            else {
                imageView = (ImageView) convertView;
            }

            if(position==lists.size()){
                imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.add_image));
                imageView.setTag("add");
            }else {
                imageView.setTag(null);
//                imageView.setTag(null);
                Bitmap bm =AppConfig.compressBySampleSize(lists.get(position).path,4);
                imageView.setImageBitmap(bm);
//                String path=lists.get(position).path;

//                if(imageCache.containsKey(path)){
//
//                    Bitmap bmCache=imageCache.get(path).get();
//
//                    if(bmCache!=null){
//                        imageView.setImageBitmap(bmCache);
//                    }
//                }else {
//                    if(path.endsWith("png")){
//                        BitmapFactory.Options options=new BitmapFactory.Options();
//                        options.inSampleSize=2;
//                        Bitmap bm = BitmapFactory.decodeFile(path,options);
//                        imageView.setImageBitmap(bm);
////                        imageCache.put(path,new SoftReference<Bitmap>(bm));
//                    }else{
//                        Bitmap bm = BitmapFactory.decodeFile(path);
//                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                        bm.compress(Bitmap.CompressFormat.JPEG, 60, baos);
//                        byte[] bytes = baos.toByteArray();
//                        bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//                        imageView.setImageBitmap(bm);
////                        imageCache.put(path,new SoftReference<Bitmap>(bm));
//                    }
//                }
            }
            return imageView;
        }
    }

}
